package com.imooc.mq;

import com.google.gson.Gson;
import com.imooc.base.BaseInfoProperties;
import com.imooc.pojo.Industry;
import com.imooc.service.IndustryService;
import com.imooc.vo.TopIdAndThirdIndustryListVO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * @author liansen
 * @create 04-04-17:08
 */
@Slf4j
@Component
public class RabbitMQDelayConsumer_Industry extends BaseInfoProperties {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IndustryService industryService;

    @RabbitListener(queues = {DelayConfig_Intustry.QUEUE_DELAY_REFRESH})
    public void watchQueue(String content, Message message, Channel channel) throws Exception {
        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        if(receivedRoutingKey.equalsIgnoreCase(DelayConfig_Intustry.DELAY_REFRESH_INDUSTRY)){
            log.info("10秒后监听到延迟队列");
            //删除redis中的一级数据
            redisTemplate.delete(TOP_INDUSTRY_LIST);
            //查询mysql中的最新数据存进redis
            List<Industry> topList = industryService.getTopList();
            redisTemplate.opsForValue().set(TOP_INDUSTRY_LIST, new Gson().toJson(topList));

            //删除redis中的三级行业数据
            Set<String> keys = redisTemplate.keys(THIRD_INDUSTRY_LIST + ":TopId:" + "*");
            redisTemplate.delete(keys);
            //查询三级行业数据后存进redis, key:THIRD_INDUSTRY_LIST + ":TopId:" + topId; value: 一级节点对应的三级列表
            List<TopIdAndThirdIndustryListVO> list = industryService.getTopIdAndThirdList();
            for(TopIdAndThirdIndustryListVO topIdAndThirdIndustryList : list){
                redisTemplate.opsForValue().set(THIRD_INDUSTRY_LIST + ":TopId:" + topIdAndThirdIndustryList.getTopId(),
                                                new Gson().toJson(topIdAndThirdIndustryList.getThirdIndustryList()));
            }
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }
}
